package com.magnificent.atlantis.client.ui.creator.tasktreetable;

import com.magnificent.atlantis.client.ui.creator.tasktreetable.data.CreatorTableModel;
import com.magnificent.atlantis.client.ui.creator.tasktreetable.data.CreatorTableNode;
import com.magnificent.atlantis.client.ui.creator.tasktreetable.data.CreatorTableShell;
import com.magnificent.atlantis.client.ui.creator.tasktreetable.renderers.CreatorTableCellRenderer;
import com.magnificent.atlantis.client.ui.creator.tasktreetable.renderers.CreatorTreeCellRenderer;
import com.magnificent.helpers.swing.TableHelper;
import org.jdesktop.swingx.JXTreeTable;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * User: Babanin
 * Date: 01.03.2009
 * Time: 19:45:22
 */
public class CreatorTreeTable extends JXTreeTable {
    public CreatorTreeTable(CreatorTableModel creatorTableModel) {
        setTreeTableModel(creatorTableModel);
        setTreeCellRenderer(new CreatorTreeCellRenderer());
        setDefaultRenderer(Object.class, new CreatorTableCellRenderer());

        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    expandRow(getSelectedRow());
                } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    CreatorTableShell tableShell = (CreatorTableShell) getValueAt(getSelectedRow(), getSelectedColumn());

                    Object[] path = CreatorTableNode.getParentPath(tableShell.getNode());
                    if (path.length > 1) {
                        collapsePath(new TreePath(path));
                    } else {
                        collapsePath(new TreePath(new Object[]{path[0], tableShell.getNode()}));
                    }
                }
            }
        });

        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public void select(int row) {
        if (row >= 0) {
            getSelectionModel().setSelectionInterval(row, row);
        }
    }

    public void select(CreatorTableNode tableNode) {
        select(find(tableNode));
    }

    public int find(CreatorTableNode tableNode) {
        int result = -1;
        for (int i = 0; i < getRowCount(); i++) {
            if (((CreatorTableShell) getValueAt(i, 0)).getNode().equals(tableNode)) {
                result = i;
                break;
            }
        }

        return result;
    }

    public void setTreeTableModel(org.jdesktop.swingx.treetable.TreeTableModel treeModel) {
        super.setTreeTableModel(treeModel);

        TableHelper.setFixedColumnSize(this, 0, 40);
        TableHelper.setFixedColumnSize(this, 1, 40);
        TableHelper.setFixedColumnSize(this, 3, 205);
    }
}